package com.asset.dispoal.file.document.service.command;

import com.asset.dispoal.file.common.FileCreateUtil;
import com.asset.dispoal.file.document.domain.db.entity.DocumentType;
import com.asset.dispoal.file.document.domain.db.entity.DocumentTypeItem;
import com.asset.dispoal.file.document.domain.db.mapper.DocumentMapper;
import com.asset.dispoal.file.document.dto.DocumentTypeAddRequest;
import com.asset.dispoal.file.document.dto.DocumentTypeItemAddRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import tech.mhuang.pacebox.core.date.DateTimeUtil;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.id.BaseIdeable;
import tech.mhuang.pacebox.core.util.CollectionUtil;
import tech.mhuang.pacebox.springboot.core.local.GlobalHeaderThreadLocal;
import tech.mhuang.pacebox.springboot.protocol.Result;

@Component
public class DocumentTypeAddCommand implements BaseCommand<DocumentTypeAddRequest, Result> {

    @Autowired
    private DocumentMapper documentMapper;

    @Autowired
    private BaseIdeable<String> idWorker;

    @Autowired
    private Environment environment;

    @Override
    public Result execute(DocumentTypeAddRequest request) {
        DocumentType documentType = new DocumentType();
        documentType.setId(idWorker.generateId());
        documentType.setName(request.getName());
        documentType.setSorted(request.getSorted());
        documentType.setCreateUserId(GlobalHeaderThreadLocal.getOrException().getUserId());
        documentType.setCreateTime(DateTimeUtil.currentDate());

        if (request.getFile() != null) {
            String headUrl = environment.getProperty("file.evidence.url");
            String appendUrl = environment.getProperty("file.documentType.url");
            String propertyUrl = FileCreateUtil.copyFile(documentType.getId(), request.getFile(), headUrl, appendUrl);
            documentType.setFileUrl(propertyUrl);
        }

        if (CollectionUtil.isNotEmpty(request.getItemList())) {
            for (DocumentTypeItemAddRequest addItem : request.getItemList()) {
                DocumentTypeItem documentTypeItem = new DocumentTypeItem();
                documentTypeItem.setId(idWorker.generateId());
                documentTypeItem.setDocumentTypeId(documentType.getId());
                documentTypeItem.setAlias(addItem.getAlias());
                documentTypeItem.setParam(addItem.getParam());
                documentTypeItem.setSorted(addItem.getSorted());
                documentMapper.insertDocumentTypeItem(documentTypeItem);
            }
        }
        documentMapper.insertDocumentType(documentType);
        return Result.ok();
    }
}
